package com.tcode.springbootweb.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.tcode.springbootweb.bean.UserBean;
import com.tcode.springbootweb.config.RestTemplateConfig;
import com.tcode.springbootweb.server.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class CustomController {
    @Autowired
    private RestTemplate rs;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private UserClient uc;


    @GetMapping("restHttp")
    public List<UserBean> restHttp(){
        List<ServiceInstance> instances = discoveryClient.getInstances("user-server");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/helloSpringBoot";
        List<UserBean> list=rs.getForObject(url, List.class);
        return list;
    }

    @GetMapping("restUser")
//    @HystrixCommand(fallbackMethod = "restUserFallBack")
    public UserBean restUser(int id){
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-server");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/findUser/"+id;
//        String url = "http://user-server/findUser/"+id;
//        UserBean user=rs.getForObject(url, UserBean.class);
        UserBean user=uc.selectUserByID(id);
        return user;
    }

    public UserBean restUserFallBack(int id){
        UserBean user =new UserBean();
        user.setUid(-1);
        user.setUname("查无此人");
        user.setPhone("号码为空");
        return user;
    }


}
